package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.entity.*;
import com.pn.taikao.service.*;
import com.pn.taikao.service.PaperStudentService;
import com.pn.taikao.service.CheatingRecordService;
import com.pn.taikao.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/exams")
public class ExamController {

    private final ExamService examService;
    private final PaperService paperService;
    private final PaperQuestionService paperQuestionService;
    private final QuestionService questionService;
    private final AnswerService answerService;
    private final ScoreService scoreService;
    private final StudentCourseService studentCourseService;
    private final UserService userService;
    private final PaperStudentService paperStudentService;
    private final CheatingRecordService cheatingRecordService;

    public ExamController(ExamService examService,
                          PaperService paperService,
                          PaperQuestionService paperQuestionService,
                          QuestionService questionService,
                          AnswerService answerService,
                          ScoreService scoreService,
                          StudentCourseService studentCourseService,
                          UserService userService,
                          PaperStudentService paperStudentService,
                          CheatingRecordService cheatingRecordService) {
        this.examService = examService;
        this.paperService = paperService;
        this.paperQuestionService = paperQuestionService;
        this.questionService = questionService;
        this.answerService = answerService;
        this.scoreService = scoreService;
        this.studentCourseService = studentCourseService;
        this.userService = userService;
        this.paperStudentService = paperStudentService;
        this.cheatingRecordService = cheatingRecordService;
    }

    /**
     * 获取学生可参加的考试列表（根据已选课程）
     */
    @GetMapping("/available")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<List<Map<String, Object>>> getAvailableExams() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        // 获取学生已选课程
        List<StudentCourse> studentCourses = studentCourseService.getByStudentId(currentUserId);
        List<Long> courseIds = studentCourses.stream()
                .map(StudentCourse::getCourseId)
                .collect(Collectors.toList());

        if (courseIds.isEmpty()) {
            return ApiResponse.success(new ArrayList<>());
        }

        // 获取这些课程的所有已发布试卷
        List<Paper> papers = new ArrayList<>();
        for (Long courseId : courseIds) {
            List<Paper> coursePapers = paperService.getPublishedByCourseId(courseId);
            papers.addAll(coursePapers);
        }

        // 过滤出当前时间在考试时间范围内的试卷
        LocalDateTime now = LocalDateTime.now();
        List<Map<String, Object>> result = new ArrayList<>();
        for (Paper paper : papers) {
            // 检查考试时间是否设置
            if (paper.getStartTime() == null || paper.getEndTime() == null) {
                continue; // 未设置考试时间的试卷不显示
            }

            // 只显示当前时间在考试时间范围内的试卷
            if (now.isAfter(paper.getEndTime())) {
                continue; // 考试已结束
            }

            // 确保状态是已发布的（双重检查）
            if (paper.getStatus() == null || !"published".equals(paper.getStatus())) {
                continue;
            }

            // 检查试卷是否发布给当前学生
            // 如果试卷有发布关系记录，则只显示发布给该学生的试卷
            // 如果没有发布关系记录（兼容旧数据），则显示所有已发布的试卷
            List<com.pn.taikao.entity.PaperStudent> paperStudents = paperStudentService.getByPaperId(paper.getId());
            if (!paperStudents.isEmpty()) {
                // 有发布关系记录，检查是否发布给当前学生
                boolean isPublishedToCurrentStudent = paperStudentService.isPublishedToStudent(paper.getId(), currentUserId);
                if (!isPublishedToCurrentStudent) {
                    continue; // 未发布给当前学生，跳过
                }
            }
            // 如果没有发布关系记录，则显示该试卷（兼容旧数据）

            Map<String, Object> paperInfo = new HashMap<>();
            paperInfo.put("paperId", paper.getId());
            paperInfo.put("paperName", paper.getName());
            paperInfo.put("courseId", paper.getCourseId());
            paperInfo.put("duration", paper.getDuration());
            paperInfo.put("startTime", paper.getStartTime());
            paperInfo.put("endTime", paper.getEndTime());

            // 检查是否已经参加考试
            Exam exam = examService.getByPaperIdAndStudentId(paper.getId(), currentUserId);
            if (exam != null) {
                paperInfo.put("examId", exam.getId());
                paperInfo.put("examStatus", exam.getStatus());
            } else {
                paperInfo.put("examId", null);
                paperInfo.put("examStatus", "not_started");
            }

            result.add(paperInfo);
        }

        return ApiResponse.success(result);
    }

    /**
     * 开始考试
     */
    @PostMapping("/start/{paperId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Long> startExam(@PathVariable("paperId") Long paperId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        try {
            Long examId = examService.startExam(paperId, currentUserId);
            return ApiResponse.success(examId);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取考试题目（不包含正确答案）
     */
    @GetMapping("/{examId}/questions")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Map<String, Object>> getExamQuestions(@PathVariable("examId") Long examId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        // 验证是否为当前学生的考试
        if (!exam.getStudentId().equals(currentUserId)) {
            return ApiResponse.error("无权限访问");
        }

        // 检查考试状态
        if ("finished".equals(exam.getStatus())) {
            return ApiResponse.error("考试已完成");
        }

        // 检查时间是否过期
        if (LocalDateTime.now().isAfter(exam.getEndTime())) {
            examService.finishExam(examId);
            return ApiResponse.error("考试时间已到");
        }

        // 获取试卷信息
        Paper paper = paperService.getById(exam.getPaperId());
        if (paper == null) {
            return ApiResponse.error("试卷不存在");
        }

        // 获取试卷题目
        List<PaperQuestion> paperQuestions = paperQuestionService.getByPaperId(paper.getId());
        List<Map<String, Object>> questions = new ArrayList<>();

        for (PaperQuestion paperQuestion : paperQuestions) {
            Question question = questionService.getById(paperQuestion.getQuestionId());
            if (question == null) {
                continue;
            }

            Map<String, Object> questionInfo = new HashMap<>();
            questionInfo.put("id", question.getId());
            questionInfo.put("type", question.getType());
            questionInfo.put("content", question.getContent());
            questionInfo.put("options", question.getOptions());
            questionInfo.put("score", paperQuestion.getScore());
            questionInfo.put("difficulty", question.getDifficulty());

            // 获取学生已保存的答案
            Answer answer = answerService.getByExamIdAndQuestionId(examId, question.getId());
            if (answer != null) {
                questionInfo.put("answer", answer.getContent());
            } else {
                questionInfo.put("answer", null);
            }

            questions.add(questionInfo);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("examId", examId);
        result.put("paperName", paper.getName());
        result.put("startTime", exam.getStartTime());
        result.put("endTime", exam.getEndTime());
        result.put("duration", exam.getDuration());
        result.put("questions", questions);

        return ApiResponse.success(result);
    }

    /**
     * 保存答案（自动保存）
     */
    @PostMapping("/{examId}/answers")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Void> saveAnswer(@PathVariable("examId") Long examId,
                                        @RequestBody Map<String, Object> request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        if (!exam.getStudentId().equals(currentUserId)) {
            return ApiResponse.error("无权限访问");
        }

        if ("finished".equals(exam.getStatus())) {
            return ApiResponse.error("考试已完成");
        }

        Long questionId = Long.valueOf(request.get("questionId").toString());
        String content = request.get("content") != null ? request.get("content").toString() : "";

        answerService.saveOrUpdateAnswer(examId, questionId, content);
        return ApiResponse.success(null);
    }

    /**
     * 提交答案
     */
    @PostMapping("/{examId}/submit")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Void> submitExam(@PathVariable("examId") Long examId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        if (!exam.getStudentId().equals(currentUserId)) {
            return ApiResponse.error("无权限访问");
        }

        if ("finished".equals(exam.getStatus())) {
            return ApiResponse.success(null); // 已提交，无需重复提交
        }

        // 获取所有答案并进行自动评分
        List<Answer> answers = answerService.getByExamId(examId);
        for (Answer answer : answers) {
            Question question = questionService.getById(answer.getQuestionId());
            if (question != null && !"essay".equals(question.getType())) {
                // 客观题自动评分
                answerService.autoScore(examId, question.getId(), answer.getContent(),
                        question.getAnswer(), question.getType());
            }
        }

        // 计算总分
        scoreService.calculateAndSaveTotalScore(examId);

        // 结束考试
        examService.finishExam(examId);

        return ApiResponse.success(null);
    }

    /**
     * 查看考试结果
     */
    @GetMapping("/{examId}/result")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Map<String, Object>> getExamResult(@PathVariable("examId") Long examId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        if (!exam.getStudentId().equals(currentUserId)) {
            return ApiResponse.error("无权限访问");
        }

        // 获取试卷信息
        Paper paper = paperService.getById(exam.getPaperId());
        if (paper == null) {
            return ApiResponse.error("试卷不存在");
        }

        // 获取成绩
        Score score = scoreService.getByExamId(examId);

        // 获取所有答案
        List<Answer> answers = answerService.getByExamId(examId);
        List<Map<String, Object>> questionResults = new ArrayList<>();

        for (Answer answer : answers) {
            Question question = questionService.getById(answer.getQuestionId());
            if (question == null) {
                continue;
            }

            Map<String, Object> questionResult = new HashMap<>();
            questionResult.put("questionId", question.getId());
            questionResult.put("type", question.getType());
            questionResult.put("content", question.getContent());
            questionResult.put("options", question.getOptions());
            questionResult.put("correctAnswer", question.getAnswer());
            questionResult.put("studentAnswer", answer.getContent());
            questionResult.put("score", answer.getScore());
            questionResult.put("teacherComment", answer.getTeacherComment());
            questionResult.put("analysis", question.getAnalysis());

            questionResults.add(questionResult);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("examId", examId);
        result.put("paperName", paper.getName());
        result.put("startTime", exam.getStartTime());
        result.put("endTime", exam.getEndTime());
        result.put("totalScore", score != null ? score.getTotalScore() : 0);
        result.put("questions", questionResults);

        return ApiResponse.success(result);
    }

    /**
     * 查看我的考试成绩列表
     */
    @GetMapping("/my-scores")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<List<Map<String, Object>>> getMyScores() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        List<Score> scores = scoreService.getByStudentId(currentUserId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (Score score : scores) {
            Exam exam = examService.getById(score.getExamId());
            if (exam == null) {
                continue;
            }

            Paper paper = paperService.getById(exam.getPaperId());
            if (paper == null) {
                continue;
            }

            Map<String, Object> scoreInfo = new HashMap<>();
            scoreInfo.put("examId", exam.getId());
            scoreInfo.put("paperName", paper.getName());
            scoreInfo.put("totalScore", score.getTotalScore());
            scoreInfo.put("endTime", exam.getEndTime());
            result.add(scoreInfo);
        }

        return ApiResponse.success(result);
    }

    /**
     * 管理员/教师：查看某个试卷的所有考试记录
     */
    @GetMapping("/paper/{paperId}/records")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<List<Map<String, Object>>> getPaperExamRecords(@PathVariable("paperId") Long paperId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        // 验证试卷是否存在
        Paper paper = paperService.getById(paperId);
        if (paper == null) {
            return ApiResponse.error("试卷不存在");
        }

        // 验证权限：教师只能查看自己创建的试卷
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!paper.getTeacherId().equals(currentUserId)) {
                return ApiResponse.error("无权限查看该试卷的考试记录");
            }
        }

        // 获取该试卷的所有考试记录
        List<Exam> exams = examService.getByPaperId(paperId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (Exam exam : exams) {
            User student = userService.getById(exam.getStudentId());
            if (student == null) {
                continue;
            }

            Score score = scoreService.getByExamId(exam.getId());

            Map<String, Object> record = new HashMap<>();
            record.put("examId", exam.getId());
            record.put("studentId", exam.getStudentId());
            record.put("studentName", student.getRealName());
            record.put("studentUsername", student.getUsername());
            record.put("startTime", exam.getStartTime());
            record.put("endTime", exam.getEndTime());
            record.put("status", exam.getStatus());
            record.put("totalScore", score != null ? score.getTotalScore() : null);
            result.add(record);
        }

        return ApiResponse.success(result);
    }

    /**
     * 管理员/教师：查看某个学生的考试详情
     */
    @GetMapping("/{examId}/detail")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Map<String, Object>> getExamDetail(@PathVariable("examId") Long examId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        // 验证权限：教师只能查看自己创建的试卷的考试记录
        Paper paper = paperService.getById(exam.getPaperId());
        if (paper == null) {
            return ApiResponse.error("试卷不存在");
        }

        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!paper.getTeacherId().equals(currentUserId)) {
                return ApiResponse.error("无权限查看该考试记录");
            }
        }

        // 获取学生信息
        User student = userService.getById(exam.getStudentId());
        if (student == null) {
            return ApiResponse.error("学生不存在");
        }

        // 获取成绩
        Score score = scoreService.getByExamId(examId);

        // 获取所有答案
        List<Answer> answers = answerService.getByExamId(examId);
        List<Map<String, Object>> questionResults = new ArrayList<>();

        for (Answer answer : answers) {
            Question question = questionService.getById(answer.getQuestionId());
            if (question == null) {
                continue;
            }

            Map<String, Object> questionResult = new HashMap<>();
            questionResult.put("questionId", question.getId());
            questionResult.put("type", question.getType());
            questionResult.put("content", question.getContent());
            questionResult.put("options", question.getOptions());
            questionResult.put("correctAnswer", question.getAnswer());
            questionResult.put("studentAnswer", answer.getContent());
            questionResult.put("score", answer.getScore());
            questionResult.put("teacherComment", answer.getTeacherComment());
            questionResult.put("analysis", question.getAnalysis());

            questionResults.add(questionResult);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("examId", examId);
        result.put("paperName", paper.getName());
        result.put("studentId", exam.getStudentId());
        result.put("studentName", student.getRealName());
        result.put("studentUsername", student.getUsername());
        result.put("startTime", exam.getStartTime());
        result.put("endTime", exam.getEndTime());
        result.put("status", exam.getStatus());
        result.put("totalScore", score != null ? score.getTotalScore() : 0);
        result.put("questions", questionResults);

        return ApiResponse.success(result);
    }

    /**
     * 管理员/教师：获取待判卷考试列表
     */
    @GetMapping("/pending-grading")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<List<Map<String, Object>>> getPendingGradingExams() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        User currentUser = SecurityUtils.getCurrentUser();
        Long teacherId = null;
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            teacherId = currentUserId;
        }

        List<Exam> exams = examService.getPendingGrading(teacherId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (Exam exam : exams) {
            Paper paper = paperService.getById(exam.getPaperId());
            if (paper == null) {
                continue;
            }

            User student = userService.getById(exam.getStudentId());
            if (student == null) {
                continue;
            }

            // 统计未评分的主观题数量
            List<Answer> answers = answerService.getByExamId(exam.getId());
            int ungradedCount = 0;
            for (Answer answer : answers) {
                Question question = questionService.getById(answer.getQuestionId());
                if (question != null && "essay".equals(question.getType())) {
                    if (answer.getScore() == null || answer.getScore().compareTo(BigDecimal.ZERO) == 0) {
                        ungradedCount++;
                    }
                }
            }

            Map<String, Object> examInfo = new HashMap<>();
            examInfo.put("examId", exam.getId());
            examInfo.put("paperId", exam.getPaperId());
            examInfo.put("paperName", paper.getName());
            examInfo.put("studentId", exam.getStudentId());
            examInfo.put("studentName", student.getRealName());
            examInfo.put("studentUsername", student.getUsername());
            examInfo.put("endTime", exam.getEndTime());
            examInfo.put("ungradedCount", ungradedCount);

            result.add(examInfo);
        }

        return ApiResponse.success(result);
    }

    /**
     * 管理员/教师：获取某个考试的答案（用于判卷）
     */
    @GetMapping("/{examId}/grading")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Map<String, Object>> getExamForGrading(@PathVariable("examId") Long examId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        // 验证权限
        Paper paper = paperService.getById(exam.getPaperId());
        if (paper == null) {
            return ApiResponse.error("试卷不存在");
        }

        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!paper.getTeacherId().equals(currentUserId)) {
                return ApiResponse.error("无权限判卷");
            }
        }

        // 获取学生信息
        User student = userService.getById(exam.getStudentId());
        if (student == null) {
            return ApiResponse.error("学生不存在");
        }

        // 获取试卷的所有题目
        List<PaperQuestion> paperQuestions = paperQuestionService.getByPaperId(exam.getPaperId());
        List<Map<String, Object>> questions = new ArrayList<>();

        for (PaperQuestion paperQuestion : paperQuestions) {
            Question question = questionService.getById(paperQuestion.getQuestionId());
            if (question == null) {
                continue;
            }

            Answer answer = answerService.getByExamIdAndQuestionId(examId, question.getId());

            Map<String, Object> questionInfo = new HashMap<>();
            questionInfo.put("questionId", question.getId());
            questionInfo.put("type", question.getType());
            questionInfo.put("content", question.getContent());
            questionInfo.put("options", question.getOptions());
            questionInfo.put("correctAnswer", question.getAnswer());
            questionInfo.put("analysis", question.getAnalysis());
            questionInfo.put("maxScore", paperQuestion.getScore());
            questionInfo.put("studentAnswer", answer != null ? answer.getContent() : "");
            questionInfo.put("score", answer != null ? answer.getScore() : BigDecimal.ZERO);
            questionInfo.put("teacherComment", answer != null ? answer.getTeacherComment() : "");

            questions.add(questionInfo);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("examId", examId);
        result.put("paperId", exam.getPaperId());
        result.put("paperName", paper.getName());
        result.put("studentId", exam.getStudentId());
        result.put("studentName", student.getRealName());
        result.put("studentUsername", student.getUsername());
        result.put("startTime", exam.getStartTime());
        result.put("endTime", exam.getEndTime());
        result.put("questions", questions);

        return ApiResponse.success(result);
    }

    /**
     * 管理员/教师：批量保存评分和评语
     */
    @PostMapping("/{examId}/grading")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> saveGrading(@PathVariable("examId") Long examId,
                                         @RequestBody List<Map<String, Object>> gradingData) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        // 验证权限
        Paper paper = paperService.getById(exam.getPaperId());
        if (paper == null) {
            return ApiResponse.error("试卷不存在");
        }

        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!paper.getTeacherId().equals(currentUserId)) {
                return ApiResponse.error("无权限判卷");
            }
        }

        // 批量保存评分
        for (Map<String, Object> item : gradingData) {
            Long questionId = Long.valueOf(item.get("questionId").toString());
            BigDecimal score = new BigDecimal(item.get("score").toString());
            String teacherComment = item.get("teacherComment") != null ? item.get("teacherComment").toString() : "";

            answerService.setScore(examId, questionId, score, teacherComment);
        }

        // 重新计算总分
        scoreService.calculateAndSaveTotalScore(examId);

        return ApiResponse.success(null);
    }

    /**
     * 管理员/教师：获取所有学生考试记录
     */
    @GetMapping("/all-records")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<List<Map<String, Object>>> getAllExamRecords(
            @RequestParam(value = "paperId", required = false) Long paperId,
            @RequestParam(value = "studentId", required = false) Long studentId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        User currentUser = SecurityUtils.getCurrentUser();
        Long teacherId = null;
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            teacherId = currentUserId;
        }

        List<Exam> exams = examService.getFinishedExams(teacherId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (Exam exam : exams) {
            Paper paper = paperService.getById(exam.getPaperId());
            if (paper == null) {
                continue;
            }

            // 按试卷ID筛选
            if (paperId != null && !paper.getId().equals(paperId)) {
                continue;
            }

            User student = userService.getById(exam.getStudentId());
            if (student == null) {
                continue;
            }

            // 按学生ID筛选
            if (studentId != null && !student.getId().equals(studentId)) {
                continue;
            }

            Score score = scoreService.getByExamId(exam.getId());

            Map<String, Object> record = new HashMap<>();
            record.put("examId", exam.getId());
            record.put("paperId", exam.getPaperId());
            record.put("paperName", paper.getName());
            record.put("studentId", exam.getStudentId());
            record.put("studentName", student.getRealName());
            record.put("studentUsername", student.getUsername());
            record.put("startTime", exam.getStartTime());
            record.put("endTime", exam.getEndTime());
            record.put("status", exam.getStatus());
            record.put("totalScore", score != null ? score.getTotalScore() : null);
            result.add(record);
        }

        return ApiResponse.success(result);
    }

    /**
     * 管理员/教师：获取成绩统计信息（所有试卷）
     */
    @GetMapping("/statistics")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<List<Map<String, Object>>> getStatistics(
            @RequestParam(value = "paperId", required = false) Long paperId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        User currentUser = SecurityUtils.getCurrentUser();
        Long teacherId = null;
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            teacherId = currentUserId;
        }

        List<Map<String, Object>> statistics;
        if (paperId != null) {
            statistics = scoreService.getStatisticsByPaperId(paperId, teacherId);
        } else {
            statistics = scoreService.getAllStatistics(teacherId);
        }

        // 处理统计数据，转换为前端需要的格式
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> stat : statistics) {
            Map<String, Object> item = new HashMap<>();
            item.put("paperId", stat.get("paperId"));
            item.put("paperName", stat.get("paperName"));
            item.put("totalCount", stat.get("totalCount") != null ? stat.get("totalCount") : 0);
            item.put("scoredCount", stat.get("scoredCount") != null ? stat.get("scoredCount") : 0);

            // 处理 BigDecimal 类型
            Object avgScore = stat.get("avgScore");
            Object maxScore = stat.get("maxScore");
            Object minScore = stat.get("minScore");

            item.put("avgScore", avgScore != null ? ((Number) avgScore).doubleValue() : 0.0);
            item.put("maxScore", maxScore != null ? ((Number) maxScore).doubleValue() : 0.0);
            item.put("minScore", minScore != null ? ((Number) minScore).doubleValue() : 0.0);

            item.put("passCount", stat.get("passCount") != null ? stat.get("passCount") : 0);
            item.put("excellentCount", stat.get("excellentCount") != null ? stat.get("excellentCount") : 0);
            item.put("goodCount", stat.get("goodCount") != null ? stat.get("goodCount") : 0);
            item.put("passLowCount", stat.get("passLowCount") != null ? stat.get("passLowCount") : 0);
            item.put("failCount", stat.get("failCount") != null ? stat.get("failCount") : 0);

            // 计算通过率
            int scored = ((Number) item.get("scoredCount")).intValue();
            int pass = ((Number) item.get("passCount")).intValue();
            double passRate = scored > 0 ? (pass * 100.0 / scored) : 0.0;
            item.put("passRate", passRate);

            result.add(item);
        }

        return ApiResponse.success(result);
    }

    /**
     * 记录作弊行为
     */
    @PostMapping("/{examId}/cheating")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Void> recordCheating(@PathVariable("examId") Long examId, @RequestBody Map<String, Object> request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }

        // 验证考试是否是当前学生的
        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }
        if (!exam.getStudentId().equals(currentUserId)) {
            return ApiResponse.error("无权限");
        }

        // 获取作弊行为信息
        String behaviorType = (String) request.get("type");
        Integer count = request.get("count") != null ? ((Number) request.get("count")).intValue() : 1;
        LocalDateTime behaviorTime;

        if (request.get("timestamp") != null) {
            try {
                behaviorTime = LocalDateTime.parse((String) request.get("timestamp"));
            } catch (Exception e) {
                behaviorTime = LocalDateTime.now();
            }
        } else {
            behaviorTime = LocalDateTime.now();
        }

        // 记录作弊行为
        cheatingRecordService.recordCheating(examId, behaviorType, count, behaviorTime);

        return ApiResponse.success(null);
    }

    /**
     * 查询考试的作弊行为记录（教师/管理员）
     */
    @GetMapping("/{examId}/cheating-records")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER')")
    public ApiResponse<List<Map<String, Object>>> getCheatingRecords(@PathVariable("examId") Long examId) {
        Exam exam = examService.getById(examId);
        if (exam == null) {
            return ApiResponse.error("考试不存在");
        }

        // 权限验证：教师只能查看自己创建的试卷的考试
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            Paper paper = paperService.getById(exam.getPaperId());
            if (paper == null || !paper.getTeacherId().equals(SecurityUtils.getCurrentUserId())) {
                return ApiResponse.error("无权限查看");
            }
        }

        List<CheatingRecord> records = cheatingRecordService.getByExamId(examId);
        List<Map<String, Object>> result = new ArrayList<>();
        for (CheatingRecord record : records) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", record.getId());
            item.put("examId", record.getExamId());
            item.put("behaviorType", record.getBehaviorType());
            item.put("behaviorCount", record.getBehaviorCount());
            item.put("behaviorTime", record.getBehaviorTime());
            item.put("createTime", record.getCreateTime());
            result.add(item);
        }

        return ApiResponse.success(result);
    }
}

